package com.my12306.train.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.my12306.common.constant.CommonConstants;
import com.my12306.common.enums.CodeEnum;
import com.my12306.common.model.vo.PageVo;
import com.my12306.common.util.PageUtils;
import com.my12306.common.util.SnowflakeIdWorker;
import com.my12306.common.util.response.ResponseData;
import com.my12306.train.constant.TrainConstant;
import com.my12306.train.dao.RateDao;
import com.my12306.train.model.entity.RateEntity;
import com.my12306.train.model.vo.RateVO;
import com.my12306.train.service.RateService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;


@Service("rateService")
public class RateServiceImpl extends ServiceImpl<RateDao, RateEntity> implements RateService {
    @Resource
    RateDao rateDao;

    @Override
    public RateEntity findFirstByType(String type) {
        QueryWrapper<RateEntity> qs = new QueryWrapper<>();
        if (type != null) {
            qs.eq("ticket_type", type);
            qs.eq("logic_delete",CommonConstants.LogicDelete.no_delet.getValue());
        }
        return rateDao.selectOne(qs);
    }



    @Override
    public ResponseData saveTickRate(RateVO rateVo) {
        if (rateVo!=null){
            RateEntity rateEntity = new RateEntity();
            BeanUtils.copyProperties(rateVo,rateEntity);
            rateEntity.setCreateDate(new Date());
            rateEntity.setUpdateDate(new Date());
            rateEntity.setId(SnowflakeIdWorker.generateId());
            if (rateVo.getIsBase().equals(TrainConstant.TICKET_BASE)){
                RateEntity rate = this.queryTicketRateByRatio(TrainConstant.TICKET_RATIO);
                if (rate!=null){
                    return ResponseData.fail(CodeEnum.ADD_FAIL.getCode(),"添加失败！原因：基础票种已经存在!");
                }
                rateEntity.setRatio(TrainConstant.TICKET_RATIO);
            }else{
                Double result = cacleTicketRatio(rateEntity.getTicketRate());
                if (result!=null) {
                    rateEntity.setRatio(result);
                }else{
                    return ResponseData.fail(CodeEnum.ADD_FAIL.getCode(),"添加失败！原因：基础票种不存在,请先添加基础票种!");
                }
            }
            this.baseMapper.insert(rateEntity);
            return ResponseData.ok();
        }
        return  ResponseData.fail(CodeEnum.ADD_FAIL.getCode(),"添加失败！原因：添加数据不能为空!");
    }

    @Override
    public void updateTicketRateById(RateEntity rate) {
        if (rate!=null){
            rate.setUpdateDate(new Date());
            if (rate.getTicketRate()!=null){
              rate.setRatio(cacleTicketRatio(rate.getTicketRate()));
            }
            this.baseMapper.updateById(rate);

        }
    }

    @Override
    public void removeTicketRateByIds(List<Long> ids) {
        if (ids!=null&&ids.size()>0){
            this.baseMapper.deleteBatchTicketRateByIds(ids,CommonConstants.LogicDelete.delete.getValue());
        }
    }

    @Override
    public PageUtils queryTicketRateByPage(PageVo pageVo) {
        pageVo.init();
        List<RateEntity> rateEntities = this.baseMapper.queryTicketRateByPage(pageVo,CommonConstants.LogicDelete.no_delet.getValue());
        int totalCount = queryTicketRateCount(pageVo, CommonConstants.LogicDelete.no_delet.getValue());
        PageUtils pageUtils = PageUtils.build(pageVo, rateEntities, totalCount);
        return pageUtils;
    }

    @Override
    public RateEntity queryTicketRateById(long id) {
        QueryWrapper<RateEntity> qw = new QueryWrapper<>();
        qw.eq("logic_delete",CommonConstants.LogicDelete.no_delet.getValue());
        qw.eq("id",id);
       return this.baseMapper.selectOne(qw);
    }

    @Override
    public RateEntity findFirstTicketRateByRatio(Double ratio) {
        QueryWrapper<RateEntity> qw = new QueryWrapper<>();
        qw.eq("logic_delete",CommonConstants.LogicDelete.no_delet.getValue());
        qw.eq("ratio",ratio);
        return this.baseMapper.selectOne(qw);
    }

    @Override
    public List<RateVO> queryAllTicketRate(int logicDelte) {
       return this.baseMapper.queryAllTicketRate(logicDelte);
    }

    /**
     * 查询数据总数据量
     * @return
     */
    private Integer queryTicketRateCount(PageVo pageVo ,Integer logicDelete){
       return this.baseMapper.queryTicketRateCount(pageVo,logicDelete);
    }

    /**
     * 内部方法
     * @param ratio
     * @return
     */
    private RateEntity queryTicketRateByRatio(double ratio){
        return   this.baseMapper.selectOne(new QueryWrapper<RateEntity>().eq("ratio",ratio).eq("logic_delete", CommonConstants.LogicDelete.no_delet.getValue()));
    }

    /**
     * 内部方法计算票率比例
     * @param ration
     * @return
     */
    private Double cacleTicketRatio(double ration){
        //查找出基础比例
        RateEntity rate = this.queryTicketRateByRatio(TrainConstant.TICKET_RATIO);
        double  result= 0D;
        if (rate!=null) {
            BigDecimal rationBigDecimal = new BigDecimal((ration / rate.getTicketRate()) * 100);
            int cacleRate = rationBigDecimal.setScale(1, BigDecimal.ROUND_UP).intValue();
           //去除小数位
            result = cacleRate;
            return result;
        }
      return null;
    }

}
